/**
 * 公共 Hook
 * @returns {{scanCode: () => void, checkRouteAndNavigate: (checkRoute: string) => void}} 返回扫一扫方法和路由检查方法
 */
export const useCommonPage = () => {
  /**
   * 检查页面栈中是否存在指定路由，存在则返回该页面，不存在则跳转到指定路由
   * @param checkRoute 需要检查的路由路径
   */
  const checkRouteAndNavigate = (checkRoute: string): void => {
    const pages = getCurrentPages();

    // 处理路由路径
    const processedCheckRoute = checkRoute.startsWith('/') ? checkRoute.slice(1) : checkRoute;
    
    // 从当前页面开始往前找检查的路由
    const index = pages.findIndex(page => page.route === processedCheckRoute);
    
    if (index !== -1) {
      // 计算需要返回的层数
      const delta = pages.length - 1 - index;
      if (delta > 0) {
        uni.navigateBack({
          delta
        });
      }
      return;
    } else {
      uni.navigateTo({
        url: '/' + checkRoute
      });
    }
  }

  /**
   * 点击扫描图标跳转打开摄像头
   */
  const scanCode = () => {
    uni.navigateTo({
      url: '/pages/BusiViews/CommonPage/scanCodeByCommodity'
    })
  }

  return {
    scanCode,
    checkRouteAndNavigate
  }
} 